package com.furentech.iotserver.fa.sinopec.sinopec_processor;

import com.furentech.iotserver.fa.sinopec.SinopecFunCode;
import com.furentech.iotserver.fa.utils.FileUtils;
import com.furentech.iotserver.fa.utils.NumberUtil;
import com.furentech.iotserver.fa.utils.SpringUtil;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

@Component
public class ReqCont_Processor extends SinopecProcessorBase {
    @Override
    String actualGetJsonString(byte[] buf) {
        return null;
    }

    @Override
    String actualGetReadableString(byte[] buf) {
        return String.format("请求下载数据内容，文件代码：0x%02x,段偏移 %d,段数%d\r\n", buf[1], NumberUtil.byte2intBE(buf, 2, 2), buf[4]);
    }

    @Override
    byte[] actualGetResponse(byte[] buf, Channel channel) {
        
        int seg = buf[4] & 0x00ff;

        /************************************从黑名单文件中读取数据内容**********************************************/
        byte[] fileReadBuf = new byte[seg * 16];
        int segOffset = 256 * (buf[2] & 0x00ff) + (buf[3] & 0x00ff);
        String filePathPrefix=System.getProperty("user.dir")+System.getProperty("file.separator");

         String fileName =filePathPrefix+ String.format("%d.dat", buf[1]);
        int actualLength=FileUtils.readFromFile(fileReadBuf, fileName, segOffset * 16+1, seg * 16);


        byte[] resByteBuf = new byte[actualLength + 5];

        byte actualSeg;

        if(actualLength % 16!=0)
        {
            actualSeg = (byte) (((actualLength / 16) & 0x00ff) + 1);
        }
        else
        {
            actualSeg = (byte) ((actualLength / 16) & 0x00ff);
        }

        resByteBuf[0] = SinopecFunCode.Data_Cont;
        resByteBuf[1] = buf[1];
        resByteBuf[2] = buf[2];
        resByteBuf[3] = buf[3];
        resByteBuf[4] = actualSeg;

        System.arraycopy(fileReadBuf, 0, resByteBuf, 5, actualLength);

        return resByteBuf;

    }
}
